<template>
  <div v-loading="loading">
    <create-sections
      title="上周孵化数据"
      class="wk-base-detail__section"
      content-height="auto">
      <el-table
        v-loading="loading"
        id="brand-table"
        :row-height="40"
        :data="mediaList"
        :summary-method="getSummaries"
        class="n-table--border el-table-header--white"
        stripe
        border
        show-summary
        highlight-current-row
        style="width: 100%;">
        <el-table-column
          v-for="(item, index) in mediaFields"
          :key="index"
          :prop="item.field"
          :label="item.label"
          :min-width="item.width ? item.width : ''"
          align="center"
          show-overflow-tooltip>
          <el-table-column
            v-for="(chlld, cIndex) in mediaFields[index].children"
            :key="cIndex"
            :prop="chlld.field + index"
            :label="chlld.label"
            :min-width="chlld.width ? chlld.width : ''"
            :formatter="fieldFormatter"
            align="center" />
        </el-table-column>
        <el-table-column
          v-if="status == 1"
          label="操作"
          align="center"
          fixed="right"
          width="100">
          <template slot-scope="scope">
            <el-dropdown
              trigger="click"
              @command="commandSelect($event, scope.row)">
              <i class="el-icon-more table-more" style="cursor: pointer" />
              <el-dropdown-menu slot="dropdown" style="width: 150px;">
                <el-dropdown-item
                  v-for="(item, index) in dropdownItems"
                  :key="index"
                  :icon="item.icon"
                  :command="item.command">{{ item.label }}</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      <div v-if="status == 1" slot="header" class="wk-base-detail__more" style="text-align: right; width: 100%;">
        <el-button type="primary" icon="el-icon-plus" circle @click="commandSelect('add')" />
      </div>
    </create-sections>

    <media-incubation-add-dialog
      v-if="formAddDialogShow"
      ref="formAdddialog"
      :title="formAddTitle"
      :form.sync="formAddForm"
      :rules="formAddRules"
      :fields="formAddFields"
      :visible.sync="formAddDialogShow"
      @pass="uploadEmployeeRelativeData"
    />
  </div>
</template>

<script>
import {
  reportMediaListQueryAPI,
  reportMediaAddOrUpdateAPI,
  reportMediaDeleteAPI
} from '@/api/oa/reportMedia'

import CreateSections from '@/components/CreateSections'
import MediaIncubationAddDialog from './MediaIncubationAddDialog'

import {
  mediaModel
} from '../model/report'
import { objDeepCopy } from '../../../../utils'

export default {
  name: 'ReportMedia',
  components: {
    CreateSections,
    MediaIncubationAddDialog
  },
  props: {
    id: [String, Number],
    status: [String, Number]
  },
  data() {
    return {
      loading: false,
      mediaList: [],
      mediaFields: [],
      // 弹窗添加
      formAddTitle: '',
      formAddForm: {},
      formAddRules: {},
      formAddFields: [],
      formAddDialogShow: false,
      dropdownItems: [{
        label: '编辑',
        command: 'update',
        icon: 'wk wk-icon-modify'
      }, {
        label: '删除',
        command: 'delete',
        icon: 'wk wk-delete'
      }],
      showTable: false
    }
  },

  computed: {},
  watch: {
    id: {
      handler() {
        this.getDetail()
      },
      immediate: true
    }
  },
  mounted() {
  },

  beforeDestroy() {
  },
  methods: {
    /**
     * 获取基础信息
     */
    getDetail() {
      this.loading = true
      reportMediaListQueryAPI(this.id, 2)
        .then(res => {
          const data = res.data || []
          this.mediaList = this.groupArr(data, 'favouriteNickname')
          this.mediaFields = objDeepCopy(mediaModel.incubationMediaFields)
          this.loading = false
          this.$nextTick()
        }).catch(() => {
          this.loading = false
        })
    },
    // 列表分组
    groupArr(list, field) {
      var obj = {}
      for (var i = 0; i < list.length; i++) {
        for (const item in list[i]) {
          if (item == field) {
            obj[list[i][item]] = {
              list: obj[list[i][field]] ? obj[list[i][field]].list : [],
              favouriteNickname: list[i][field]
            }
          }
        }
        obj[list[i][field]].list.push(list[i])
      }
      var att = []
      for (const item in obj) {
        att.push({
          children: obj[item].list,
          favouriteNickname: obj[item].favouriteNickname
        })
      }
      return att
    },

    /**
     * 格式化字段
     */
    fieldFormatter(row, column, cell, rowIndex) {
      const index = Number(column.property.substring(column.property.length - 1)) - 1
      const property = column.property.substring(0, column.property.length - 1)
      if (property == 'completedWeek') {
        return row.children[index] ? (row.children[index][property] || 0) + '%' : '0%'
      } else {
        return row.children[index] ? row.children[index][property] || '--' : '--'
      }
    },

    // 上周孵化数据合计
    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === columns.length - 1) {
          sums[index] = ''
          return
        }
        if (index === 0) {
          sums[index] = '合计'
          return
        }
        if (index > 0 && (index + 1) % 4 == 0) {
          sums[index] = ((Math.floor(sums[index - 1] * 100 / sums[index - 2])) || 0) + '%'
          return
        }
        if ((index + 1) % 4 == 1) {
          sums[index] = '--'
          return
        }
        const values = []
        const cIndex = Number(column.property.substring(column.property.length - 1)) - 1
        const property = column.property.substring(0, column.property.length - 1)
        data.forEach(item => {
          if (item.children && item.children[cIndex]) {
            values.push(Number(item.children[cIndex][property]))
          }
        })
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
        } else {
          sums[index] = ''
        }
      })
      return sums
    },

    /**
     * 提交数据
     */
    uploadEmployeeRelativeData() {
      const addForm = objDeepCopy(this.formAddForm)
      const param = []
      addForm.reportId = this.id
      addForm.children.forEach(item => {
        item.reportId = this.id
        item.favouriteNickname = addForm.favouriteNickname
        param.push(item)
      })
      reportMediaAddOrUpdateAPI(param).then(res => {
        this.$message.success(`${this.formAddTitle}成功`)
        this.formAddDialogShow = false
        this.getDetail()
      }).catch(() => {
        this.formAddDialogShow = false
      })
    },

    /**
     * 编辑删除操作
     */
    commandSelect(command, data) {
      if (command == 'delete') {
        this.$confirm('确定要删除吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          reportMediaDeleteAPI(data.id).then(res => {
            this.$message({
              type: 'success',
              message: '删除成功'
            })
            this.getDetail()
          }).catch(() => {})
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消操作'
          })
        })
      } else if (command == 'update') {
        // 孵化数据
        this.formAddFields = objDeepCopy(mediaModel.incubationMediaFields)
        this.formAddFields.forEach(item => {
          if (item.children) {
            item.children.forEach(child => { child.name = child.label })
          }
        })

        this.formAddForm = objDeepCopy(data)
        this.formAddDialogShow = true
        this.formAddTitle = '编辑数据'
        this.formAddRules = mediaModel.incubationMediaRules
        this.formAddFields.forEach(item => {
          item.name = item.label
        })
        this.formAddDialogShow = true
      } else if (command == 'add') {
        // 孵化数据
        this.formAddFields = objDeepCopy(mediaModel.incubationMediaFields)
        this.formAddFields.forEach(item => {
          if (item.children) {
            item.children.forEach(child => { child.name = child.label })
          }
        })
        const parentForm = {
          favouriteNickname: ''
        }
        const children = []
        for (let i = 1; i < 5; i++) {
          const form = objDeepCopy(mediaModel.form)
          form.period = 'THIS'
          form.dataType = 2
          form.dataField = i
          children.push(form)
        }
        parentForm.children = children
        this.formAddForm = parentForm

        this.formAddTitle = '新增数据'
        this.formAddRules = mediaModel.incubationMediaRules
        this.formAddFields.forEach(item => {
          item.name = item.label
        })
        this.formAddDialogShow = true
      }
    }
  }
}
</script>

<style>
</style>

<style lang="scss" scoped>
.base-add-button {
  width: 100%;
  margin: 10px 0;
  padding: 11px 12px;
}

.wk-base-detail-section + .wk-base-detail-section {
  border-top: 1px solid $xr-border-color-base;
}

.create-sections {
  /deep/ .create-sections-content {
    padding: 0 20px;
  }
}

.contract-files {
  width: 80%;
  margin: 20px 0 20px 10px;
}

/deep/ .el-table__footer-wrapper div {
  color: red;
  font-size: 14px;
  font-weight: bold;
}
</style>
